<?php
/*
 * @Author       : chaihao
 * @Date         : 2020-06-01 14:30:22
 * @FilePath     : /xunao/ai/Services/api/SeatService.php
 */

namespace app\Services\api;

use yii;
use app\commands\Helper;
use app\commands\ErrorMsg;
use app\models\Ivtcode;
use app\models\Room;
use app\models\Seat;
use app\models\Seattimeline;
use app\models\User;
use app\models\UserAvter;
use app\models\UserLimit;
use app\Services\ApiService;
use Exception;
use yii\helpers\ArrayHelper;

class SeatService extends ApiService
{

    /**
     * @return Service_Pay
     */
    public static function getInstance()
    {
        return parent::getInstance();
    }

    /**
     * 房间内占座情况
     */
    public function getSeatInfo($room_id)
    {
        $roomData = Seat::find()->where(['roomID' => $room_id])
            ->select(['ID', 'line', 'seatdate', 'updatetime', 'index'])
            ->orderBy(['line' => SORT_ASC])
            ->asArray()
            ->all();
        $line = array_column($roomData, null, 'line');
        if (!empty($line)) {
            foreach ($line as $key => $item) {
                $seatdate = explode('/', $item['seatdate']);
                $user_id = array_filter($seatdate, function ($v) {
                    if ($v >= 1) {
                        return $v;
                    }
                });
                $userModInfo  = [];
                $userNicknameInfo  = [];
                if (!empty($user_id)) {
                    // 获取用户模型ID
                    $userMod =  UserAvter::find()->where(['in', 'userID', $user_id])->orderBy(['ID' => SORT_DESC])->select(['modID', 'userID'])->asArray()->all();
                    // 获取用户nickname
                    $userNickname = User::find()->where(['in', 'ID', $user_id])->orderBy(['ID' => SORT_DESC])->select(['ID', 'Nickname'])->asArray()->all();
                    $userLimit = UserLimit::find()->where(['in', 'userID', $user_id])->asArray()->all();
                    $userModInfo = array_column($userMod, 'modID', 'userID');
                    $userNicknameInfo = array_column($userNickname, 'Nickname', 'ID');
                    $userLimitInfo = array_column($userLimit, null, 'userID');
                }
                $data[$key] = [];
                foreach ($seatdate as $k => $v) {
                    $info = [
                        'userid' => $v,
                        'modid' => $v,
                        'nickname' => '',
                        'message' => '-1',
                        'card' => '-1',
                    ];
                    if ($v >= 1) {
                        $info = [
                            'userid' => $v,
                            'modid' => $userModInfo[$v] ?? $v,
                            'nickname' => $userNicknameInfo[$v] ?? '',
                            'message' => isset($userLimitInfo[$v]) ? $userLimitInfo[$v]['message'] : '-1',
                            'card' => isset($userLimitInfo[$v]) ? $userLimitInfo[$v]['card'] : '-1',
                        ];
                    }
                    $data[$key][]  = $info;
                    unset($info);
                }
                unset($user_id);
            }

            // // print_r($data);
            // $str = '';
            // foreach ($data as $item) {
            //     $implode = implode('/', $item);
            //     $str .= $implode . '<br/>';
            // }
            return ['code' => 200, 'data' => ['result' => array_values($data), 'index' => $roomData[0]['index']]];
        }
        return ['code' => 200, 'data' => [], 'message' => '暂无数据'];
    }

    /**
     * 返回SeattimeInfo表中比传参时间大的所有status=1和2的记录
     *
     * @param [type] $room_id
     * @param [type] $updatetime
     * @return void
     */
    public function seattimeInfo($room_id, $updatetime)
    {
        $data = Seattimeline::find()->where(['>', 'updatetime', $updatetime])
            ->andWhere(['roomID' => $room_id])
            ->andWhere(['in', 'status', ['1', '2']])->select(['row', 'col', 'status', 'updatetime'])
            ->asArray()->all();
        $content = '';
        if (count($data) >= 1) {
            for ($i = 0; $i < count($data); $i++) {
                $info = $data[$i];
                $content .= $info['row'] . '/' . $info['col'] .  '/' . $info['status'] . '/' . $info['updatetime'] . '</br>';
                unset($info);
            }
            // 返回SeattimeInfo表中比传参时间大的所有status=1和2的记录
            return ['code' => 200, 'data' => trim($content, '</br>')];
        }
        return ['code' => -1, 'message' => 'NoData'];
    }
    /**
     * 返回seattimeline表中时间大于updatetime的所有status=1和2的记录
     *
     * @param [type] $room_id
     * @param [type] $updatetime
     * @return void
     */
    public function updateMod($room_id, $index)
    {
        $data = Seattimeline::find()
            ->where(['>', 'ID', $index])
            ->andWhere(['roomID' => $room_id])
            ->andWhere(['in', 'status', ['1', '2', '3']])->select(['row', 'col', 'status', 'userID', 'ID'])
            ->asArray()
            ->all();
        $userID = array_column($data, 'userID');
        if (!empty($userID)) {
            $userAvter =  UserAvter::find()->where(['in', 'userID', $userID])->select(['userID', 'modID'])
                ->asArray()->all();
            $userNickname = User::find()->where(['in', 'ID', $userID])->select(['ID', 'Nickname'])->asArray()->all();
            $userLimit = UserLimit::find()->where(['in', 'userID', $userID])->asArray()->all();
            $userNicknameInfo = array_column($userNickname, 'Nickname', 'ID');
            $userAvterInfo = array_column($userAvter, 'modID', 'userID');
            $userLimitInfo = array_column($userLimit, null, 'userID');
        }
        // print_r($userLimitInfo);
        $content = '';
        if (count($data) >= 1) {
            foreach ($data as &$item) {
                $item['modID'] = $userAvterInfo[$item['userID']] ?? '';
                $item['userID'] = $item['userID'];
                $item['nickname'] = $userNicknameInfo[$item['userID']] ?? '';
                $item['message'] = isset($userLimitInfo[$item['userID']]) ? $userLimitInfo[$item['userID']]['message'] : '-1';
                $item['card'] = isset($userLimitInfo[$item['userID']]) ? $userLimitInfo[$item['userID']]['card'] : '-1';
                $content .= $item['row'] . '/' . $item['col'] . '/' . $item['modID'] . '/' . $item['status'] . '/' . $item['ID'] . '/' . $item['userID'] . '/' . $item['nickname'] . '/' . $item['message'] . '/' . $item['card'] . '</br>';
            }

            // 返回SeattimeInfo表中比传参时间大的所有status=1和2的记录
            return ['code' => 200, 'data' => trim($content, '</br>')];
        }
        return ['code' => -1, 'message' => 'NotUpdate'];
    }

    /**
     * 离开座位
     *
     * @param [type] $data
     */
    public function quitSeat($data)
    {
        // 添加离开状态数据接口，当状态为 1 => 进入 时禁止添加数据
        if ($data['status'] == 1) {
            return ['code' => -1, 'message' => '状态参数错误'];
        }
        $info = [
            'roomID' => $data['roomid'],
            'row' => $data['row'],
            'col' => $data['col'],
            'userID' => $data['user_id'],
            'status' => $data['status'],
            'updatetime' => date('Y-m-d H:i:s', time()),
        ];

        $result = Yii::$app->db->createCommand()->insert(Seattimeline::tableName(), $info)->execute();
        $content = Seattimeline::DEFAULT_STATUS_VALUE[$data['status']] ?? '';
        if ($result) {
            if ($result) {
                return ['code' => 200, 'message' =>  $content . '成功'];
            }
            return ['code' => -1, 'message' => $content . '失败'];
        }
    }

    /**
     * 返回seattimeline表与传参roomid和userid相符的最后一条记录
     *
     * @param [type] $room_id
     * @param [type] $user_id
     * @return void
     */
    public function checkHeart($room_id, $user_id)
    {
        $data = Seattimeline::find()->where(['roomID' => $room_id, 'userID' => $user_id])->orderBy(['id' => SORT_DESC])->asArray()->one();
        $content = '';
        if (!empty($data)) {
            $content = $data['row'] . '/' . $data['col'] . '/' . $data['status'] . '/' . $data['updatetime'];
            return ['code' => 200, 'data' =>  $content];
        }
        return ['code' => -1, 'message' => 'isFirst'];
    }

    /**
     * 返回seattimeline表中updatetime大于传参的status=2 or 4 or 5 or 6的记录
     *
     * @param [type] $data
     */
    public function getLiveHeart($data)
    {
        $status = explode(',', $data['status']);
        $result =  Seattimeline::find()->where(['>', 'ID', $data['index']])
            ->andWhere(['in', 'status', $status])
            ->select('ID,userID, roomID, row, col, status, updatetime')
            ->asArray()
            ->all();
        $content = '';
        if (count($result) >= 1) {
            for ($i = 0; $i < count($result); $i++) {
                $info = $result[$i];
                $content .= $info['userID'] . '/' . $info['roomID'] . '/' . $info['row'] . '/' . $info['col'] . '/' . $info['status'] . '/' . $info['updatetime'] . '/' . $info['ID'] . '</br>';
                unset($info);
            }
        }
        if (empty($content)) {
            return  ['code' => -1, 'message' => '未查找到数据'];
        }
        return ['code' => 200, 'data' => trim($content, '</br>')];
    }
    /**
     * 在seattimeline表中插入传参数值的一条记录
     *
     * @param [type] $data
     * @return void
     */
    public function updateLiveHeart($data)
    {
        // 重组数据
        $info = [
            'roomID'  => $data['roomid'],
            'row' => $data['row'],
            'col' => $data['col'],
            'status' => $data['status'],
            'userID' => $data['user_id'],
            'updatetime' => date('Y-m-d H:i:s', time()),
        ];
        try {
            Yii::$app->db->createCommand()->insert(Seattimeline::tableName(), $info)->execute();
            return ['code' => 200, 'message' => '操作成功'];
        } catch (Exception $e) {
            return ['code' => -1, 'message' => $e->getMessage()];
        }
    }

    /**
     *  该方法已弃用  （现使用 updateSeatByIndex ）
     * 
     * 使用seattimelimit表更新seat表，每次调用更新一次。seattimeline表中satus=1的则在seat表对应位置将0改为userid， satus=2则将userid改为0
     *
     */
    public function updateSeat()
    {
        $roomID = Room::find()->select(['ID'])->asArray()->column();
        foreach ($roomID as $room_id) {
            // 历史更新时间
            $updatetime = Seat::find()->where(['roomID' => $room_id])
                ->select(['updatetime'])
                ->asArray()
                ->scalar();
            // 获取比当前时间大的所有更新数据
            $roomDatas =  Seattimeline::find()->where(['>', 'updatetime', $updatetime])->andWhere(['roomID' => $room_id])
                ->select(['roomID', 'row', 'col', 'userID', 'status', 'updatetime'])
                ->orderBy(['updatetime' => SORT_DESC])
                ->asArray()
                ->all();

            unset($updatetime);
            // exit;
            if (!empty($roomDatas)) {
                // Seattimeline表当前房间最新更新时间
                $up_updatetime =  $roomDatas[0]['updatetime'];
                // 按照更新时间升序排序
                ArrayHelper::multisort($roomDatas, 'updatetime', SORT_ASC);
                // 以行进行分组 保留每行最新值
                $rowData =  ArrayHelper::index($roomDatas, null, 'row');
                // 获取当前房间所有行
                $roomLineData = Seat::find()->where(['roomID' => $room_id])
                    ->select(['ID', 'line', 'seatdate'])
                    ->asArray()
                    ->all();
                if (!empty($roomLineData)) {
                    foreach ($roomLineData as $k => $lineData) {
                        $new_seatdate = $lineData['seatdate'];
                        if (isset($rowData[$lineData['line']])) {
                            $colData = $rowData[$lineData['line']]; // 当前行修改信息
                            // 按照更新时间升序排序
                            ArrayHelper::multisort($colData, 'updatetime', SORT_ASC);
                            // 保留列最新值，最新列数据信息
                            $item_col = array_column($colData, null, 'col');
                            // Yii::info($item_col, '$item_col');

                            $lineCol = explode('/', $lineData['seatdate']);
                            // Yii::info($item_col , '$item_col');
                            foreach ($item_col  as $col => $item) {
                                if ($item['status'] == 1 || $item['status'] == 5) {
                                    $lineCol[$col - 1] = $item['userID'];
                                } elseif (in_array($item['status'], [2, 3])) {
                                    $lineCol[$col - 1] = 0;
                                    // 获取邀请码绑定信息
                                    $binging =  Ivtcode::find()->where(['binging' => $item['userID']])->asArray()->one();
                                    if (!empty($binging) && $binging['row'] > 0 && $binging['col'] > 0) {
                                        $lineCol[$col - 1] = -1;
                                    }
                                }
                            }
                            $new_seatdate = implode('/', $lineCol);
                        }
                        // 修改数据
                        try {
                            Yii::info($new_seatdate, '$new_seatdate');
                            Yii::$app->db->createCommand()->update(Seat::tableName(), ['seatdate' => $new_seatdate, 'updatetime' => $up_updatetime], ['ID' => $lineData['ID']])->execute();
                        } catch (Exception $e) {
                            return ['code' => -1, 'message' => $e->getMessage()];
                        }
                    }
                    unset($roomLineData);
                    unset($rowData);
                }
                unset($roomDatas);
            }
        }
        return ['code' => 200, 'message' => '操作成功'];
    }
    /**
     * 确认选座
     */
    public function confirmSeat($data)
    {
        $info = [
            'roomID' => $data['roomid'],
            'row' => $data['row'],
            'col' => $data['col'],
            'userID' => $data['user_id'],
            'status' => Seattimeline::DEFAULT_STATUS_IN, // 确认选座 参数 等于 1
            'updatetime' => date('Y-m-d H:i:s', time()),
        ];
        //获取座位当前状态
        $status =  Seattimeline::find()->where(['roomID' => $info['roomID'], 'row' => $info['row'], 'col' => $info['col']])
            ->orderBy(['ID' => SORT_DESC])
            ->select(['status'])
            ->scalar();
        if (isset($status) && in_array($status, [Seattimeline::DEFAULT_STATUS_IN, Seattimeline::DEFAULT_STATUS_DOWN])) {
            return ['code' => -1, 'message' => 'occupied'];
        }
        $content = Seattimeline::DEFAULT_STATUS_VALUE[Seattimeline::DEFAULT_STATUS_IN] ?? '';
        try {
            Yii::$app->db->createCommand()->insert(Seattimeline::tableName(), $info)->execute();
            return ['code' => 200, 'message' =>  $content . '成功'];
        } catch (Exception $e) {
            return ['code' => -1, 'message' => $content . "失败"];
        }
    }
    /**
     * 更新在线状态
     *
     */
    public function onlineState()
    {
        // $second = 120;
        // // 设置当前时间前120秒时间
        // $date = date('Y-m-d H:i:s', (time() - $second));
        // // 获取 2 分钟内的所有信息
        // $dataAll =  Seattimeline::find()->where(['>', 'updatetime', $date])
        //     ->orderBy(['ID' => SORT_ASC])
        //     ->asArray()
        //     ->all();

        // if (!empty($dataAll)) { // 存在掉线成员
        //     // 按房间分组
        //     $roomInfo = ArrayHelper::index($dataAll, null, 'roomID');
        //     // Yii::info($roomInfo, '$roomInfo');
        //     foreach ($roomInfo as $room_id => $room) {
        //         // 过滤用户
        //         ArrayHelper::multisort($room, 'ID', SORT_ASC);
        //         // 根据userID 只保留最新一条信息
        //         $roomUser = array_column($room, null, 'userID');
        //         // Yii::info($roomUser, '$roomUser');
        //         // 过滤数据
        //         $dataResult = [];
        //         foreach ($roomUser as $key => $item) {
        //             // 最后一条信息为 4 或 5 且已经超过 50s 未收到消息
        //             if (in_array($item['status'], ['1', '4', '5']) && ((time() - strtotime($item['updatetime'])) > 50)) {
        //                 $dataResult[] = $item;
        //             }
        //         }
        //         if (!empty($dataResult)) {
        //             $dataInfo = [];
        //             $num[$room_id] = 0;
        //             $statusInfo = ArrayHelper::index($dataResult, null, 'status');
        //             // print_r($statusInfo);
        //             foreach ($statusInfo as $status => $info) {
        //                 if ($status === 4) { // 用户未选座, 无行列信息
        //                     $user_ids = array_column($info, 'userID');
        //                     foreach ($user_ids as  $user_id) {
        //                         $dataInfo[] = [
        //                             'roomID' => $room_id,
        //                             'userID' => $user_id,
        //                             'row' => 0,
        //                             'col' => 0,
        //                             'status' => 6,
        //                             'updatetime' => date('Y-m-d H:i:s', time()),
        //                         ];
        //                         $num[$room_id] += 1;
        //                     }
        //                 } elseif ($status === 5 || $status === 1) { // 用户已坐下，存在行列信息
        //                     foreach ($info as $k => $v) {
        //                         $dataInfo[] = [
        //                             'roomID' => $room_id,
        //                             'userID' => $v['userID'],
        //                             'row' => $v['row'],
        //                             'col' => $v['col'],
        //                             'status' => 2,
        //                             'updatetime' => date('Y-m-d H:i:s', time()),
        //                         ];
        //                         $num[$room_id] += 1;
        //                     }
        //                 }
        //             }


        //             // Yii::info($dataInfo, '$dataInfo');
        //             if (!empty($dataInfo)) {
        //                 $transaction =  Yii::$app->db->beginTransaction();
        //                 // Yii::info($num, '$num');
        //                 try {
        //                     if (!empty($num)) {
        //                         foreach ($num as $room_id => $item) {
        //                             if ($item > 0) {
        //                                 // 获取房间人数
        //                                 $roomInfo =  Room::find()->where(['ID' => $room_id])->asArray()->one();
        //                                 if (!empty($roomInfo) && $roomInfo['curseat'] - $item >= 0) {
        //                                     $curseat = $roomInfo['curseat'] - $item;
        //                                 } else {
        //                                     $curseat = 0;
        //                                 }
        //                                 Yii::$app->db->createCommand()->update(Room::tableName(), ['curseat' => $curseat], ['ID' => $room_id])->execute();
        //                                 unset($roomInfo);
        //                             }
        //                         }
        //                     }
        //                     Yii::$app->db->createCommand()->batchInsert(Seattimeline::tableName(), array_keys($dataInfo[0]), array_map('array_values', $dataInfo))->execute();
        //                     $transaction->commit();
        //                 } catch (Exception $e) {
        //                     $transaction->rollBack();
        //                     return ['code' => '-1', 'message' => $e->getMessage()];
        //                 }
        //             }
        //         }
        //     }
        // }
        // return ['code' => '200', 'message' => '操作成功'];
    }





    /**
     * 使用seattimelimit表更新seat表，每次调用更新一次。seattimeline表中satus=1的则在seat表对应位置将0改为userid， satus=2则将userid改为0
     */
    public function updateSeatByIndex()
    {
        // $roomID = Room::find()->select(['ID'])->asArray()->column();
        // foreach ($roomID as $room_id) {
        //     // 历史更index
        //     $index = Seat::find()->where(['roomID' => $room_id])
        //         ->select(['index'])
        //         ->asArray()
        //         ->scalar();
        //     // 获取比 index 大的所有更新数据
        //     $roomDatas =  Seattimeline::find()->where(['roomID' => $room_id])
        //         ->andFilterWhere(['>', 'ID', $index])
        //         ->select(['ID', 'roomID', 'row', 'col', 'userID', 'status', 'updatetime'])
        //         ->orderBy(['ID' => SORT_DESC])
        //         ->asArray()
        //         ->all();
        //     // Yii::info($roomDatas, '$roomDatas');
        //     unset($updatetime);
        //     // exit;
        //     if (!empty($roomDatas)) {
        //         // Seattimeline表当前房间最新更新时间
        //         $up_updatetime =  $roomDatas[0]['updatetime'];
        //         $up_index =  $roomDatas[0]['ID'];
        //         // Yii::info($up_index, '$up_index');
        //         // 按照更新index升序排序
        //         ArrayHelper::multisort($roomDatas, 'index', SORT_ASC);
        //         // 以行进行分组 保留每行最新值
        //         $rowData =  ArrayHelper::index($roomDatas, null, 'row');
        //         // 获取当前房间所有行
        //         $roomLineData = Seat::find()->where(['roomID' => $room_id])
        //             ->select(['ID', 'line', 'seatdate'])
        //             ->asArray()
        //             ->all();
        //         if (!empty($roomLineData)) {
        //             foreach ($roomLineData as $k => $lineData) {
        //                 $new_seatdate = $lineData['seatdate'];
        //                 if (isset($rowData[$lineData['line']])) {
        //                     $colData = $rowData[$lineData['line']]; // 当前行修改信息
        //                     // 按照更新时间升序排序
        //                     ArrayHelper::multisort($colData, 'index', SORT_ASC);
        //                     // 保留列最新值，最新列数据信息
        //                     $item_col = array_column($colData, null, 'col');
        //                     // Yii::info($item_col, '$item_col');

        //                     $lineCol = explode('/', $lineData['seatdate']);
        //                     // Yii::info($item_col , '$item_col');
        //                     foreach ($item_col  as $col => $item) {
        //                         if ($item['status'] == 1 || $item['status'] == 5) {
        //                             $lineCol[$col - 1] = $item['userID'];
        //                         } elseif (in_array($item['status'], [2, 3])) {
        //                             $lineCol[$col - 1] = 0;
        //                             // 获取邀请码绑定信息
        //                             $binging =  Ivtcode::find()->where(['binging' => $item['userID']])->asArray()->one();
        //                             if (!empty($binging) && $binging['row'] > 0 && $binging['col'] > 0) {
        //                                 $lineCol[$col - 1] = -1;
        //                             }
        //                         }
        //                     }
        //                     $new_seatdate = implode('/', $lineCol);
        //                 }
        //                 // 修改数据
        //                 try {
        //                     Yii::info($new_seatdate, '$new_seatdate');
        //                     Yii::$app->db->createCommand()->update(Seat::tableName(), ['seatdate' => $new_seatdate, 'updatetime' => $up_updatetime, 'index' => $up_index], ['ID' => $lineData['ID']])->execute();
        //                 } catch (Exception $e) {
        //                     return ['code' => -1, 'message' => $e->getMessage()];
        //                 }
        //             }
        //             unset($roomLineData);
        //             unset($rowData);
        //         }
        //         unset($roomDatas);
        //     }
        // }
        // return ['code' => 200, 'message' => '操作成功'];
    }
}
